package com.thrsdk.common.base;

import android.text.TextUtils;
import android.util.Log;

import com.thrsdk.utils.GsonUtils;
import com.thrsdk.constants.AppConstants;
import com.thrsdk.model.data.DeviceInfo;
import com.thrsdk.utils.SecurityUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;

/**
 * Created on 2021/7/29.
 */
public class BaseParams<T> {

    private HashMap<String,String> params = new HashMap<>();

    private T data;

    public BaseParams(DeviceInfo deviceInfo, T data) {
        this.data = data;

        params.put("appId", String.valueOf(AppConstants.appId));
//        params.put("requestid", String.valueOf(System.currentTimeMillis()));
        params.put("sdkversion", AppConstants.sdkVer);
//        params.put("pkversion", deviceInfo.getAppVersion());
//        params.put("sessid", AppConstants.Sessid);
//        params.put("token", AppConstants.Token);
//        params.put("openid", AppConstants.openid);
    }

    public HashMap<String, String> getParams(){
        if (data != null){
            HashMap<String, String> dataMap = GsonUtils.createObj(GsonUtils.getInstance().toJson(data));
            for (HashMap.Entry<String, String> entry : dataMap.entrySet()) {
                //临时处理package关键字问题,后续需要更换字段名
                if (TextUtils.equals(entry.getKey(),"packageName")){
                    params.put("package",entry.getValue());
                } else {
                    params.put(entry.getKey(),entry.getValue());
                }
            }
        }
        params.put("sign", assignSign());
        return params;
    }

    //加密
    private String assignSign() {
        StringBuffer sign = new StringBuffer();
        Object[] keyArr = params.keySet().toArray();
        Arrays.sort(keyArr);
        for (Object key : keyArr) {
            String value = params.get(key) == null ? "" : params.get(key);
            sign.append(value);
        }
        sign.append(AppConstants.appKey);
        String ecode= null;
        try {
            ecode = URLEncoder.encode(sign.toString(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.e("原始sign", ecode);
        return SecurityUtils.getMD5Str(ecode);

    }
}
